package pak.Random;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;

public class RandomName {
    public static void main(String[] args) throws IOException {
        JFrame jf = new JFrame();
        jf.setTitle("随机点名器");
        jf.setSize(400, 500);
        jf.setLocationRelativeTo(null);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setLayout(new BorderLayout());
        JPanel center = new JPanel();
        center.setLayout(new FlowLayout(FlowLayout.LEFT));
        InputStreamReader reader = new InputStreamReader(RandomName.class.getClassLoader().getResourceAsStream("names.txt"), "UTF-8");
        BufferedReader br = new BufferedReader(reader);
        String name;
        while ((name = br.readLine()) != null) {
            JButton jb = new JButton(name);
            jb.setBackground(new Color(0xEAFFFF));
            center.add(jb);
        }
        br.close();//关闭流操作
        jf.add(center, BorderLayout.CENTER);
        JPanel south = new JPanel();
        JButton jb = new JButton("抽奖");
        south.add(jb);
        jf.add(south, BorderLayout.SOUTH);
        jb.addActionListener(new AbstractAction() {
            Random r = new Random();
            Thread t;

            @Override
            public void actionPerformed(ActionEvent e) {
                if (jb.getText().equals("抽奖")) {
                    jb.setText("停止");
                    // 做抽奖的事情。
                    Component[] names = center.getComponents();
                    for (int i = 0; i < names.length; i++) {
                        names[i].setForeground(Color.BLACK);
                    }


                    //闪烁的效果 == 随机抽到一个 变红 等0.1秒 再变黑  再随机抽一下 变红 .
                    t = new Thread(() -> {
                        while (true) {
                            int index = r.nextInt(names.length);
                            names[index].setForeground(Color.RED);

                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e1) {
                                e1.printStackTrace();
                            }
                            names[index].setForeground(Color.BLACK);
                        }
                    });
                    t.start();
                } else {
                    jb.setText("抽奖");
                    // 需要把 线程终止掉。
                    t.stop();
                }
            }
        });
        jf.setVisible(true);
    }
}